//
//  XLGUpdateSessionInternal.m
//  etionCBLogic
//
//  Created by wjxfhxy on 15-4-29.
//  Copyright (c) 2015年 GuangZhouXuanWu. All rights reserved.
//

#import "XLGUpdateSessionInternal.h"

#import "CGWService+ChannelProocol.h"

#define CHECK_TIME_INTERVAL 900    //每900秒获取一次网络时间用于校验

@implementation XLGUpdateSessionInternal
{
    NSTimer *_timer;
    BOOL _bRunning;
}

- (XLGResult*)updateSession
{
    return [[self service] sendChannelProtocol:^CProtocolBase *
    {
        return [[XLGUpdateSessionChannelProtocol new] updateSessionProtocol];
    }];
}

- (void)addUpdateSessionTimer:(NSTimer *)timer
{
    [super requestAsyncBlock:^
    {
        if (self.isCanRequest == NO)
            return;
        
        if (NO == [XLGContext context].m_bIsoffline)
            [self updateSession];
    }];
}

- (int)initUpdateSessionTimer
{
    if (YES == [XLGContext context].m_bIsoffline)
        return NETWORKOFFLINE;
    
    if (YES == [XLGContext context].m_bIsofflinelogin)
        return NETWORKOFFLINE;

    if (_bRunning == YES)
        return YES;
    
    _bRunning = YES;
    
    if (_timer == nil)
    {
        _timer = [[NSTimer timerWithTimeInterval:CHECK_TIME_INTERVAL target:self selector:@selector(addUpdateSessionTimer:) userInfo:nil repeats:YES] retain_mm];
        [[NSRunLoop mainRunLoop] addTimer:_timer forMode:NSDefaultRunLoopMode];
    }
    return YES;
}

- (void)releaseUpdateSessionTimer
{
    [self stopRequest];
    _bRunning = NO;
    [_timer invalidate];
    ReleaseObj(_timer);
}

- (void)foregroundCheckSessionIsTimeoutAsyncCompletion:(void(^)(NSInteger nResult,BOOL bIstimeout))completion
{
    EDOMRequestStateType type = [self requestAsyncBlock:^
    {
        XLGResult *r = [self updateSession];
        
        completion(r.outResult,![(NSNumber*)r.outObj boolValue]);
    }];
    if(EDOMRequestStateTypeCanNotRequest== type)
        completion(TERMINATEREADWRITE,FALSE);
}

- (void)dealloc
{
    [self releaseUpdateSessionTimer];
    superdealloc_mm;
}

@end
